var DocData={
    billingURL:'/xrtn-manager/order/gotoFastOrder',
    bookingInfoDetailURL:'/xrtn-manager/booking/gotoBespeakInfoDetail',
    sendBooking:false,
    bookingInfo:{
        userId:'',
        userName:'',
        userPhone:"",
        patientId:'',
        bookingTime:baseFn.getQueryString('bookingTime',true),
        doctorId:baseFn.getQueryString('doctorId',true),
        subclinicId:baseFn.notNull(baseFn.getQueryString('subclinicId',true))?baseFn.getQueryString('subclinicId',true):SessionData.subclinicId,
    },
    subclinicList:[],
    patientList:[],
    patientInfo:{},
    newRenderBooking:function(data){
        var _opts = $.extend({},{
            edit:false,
            update:false,//更新 true 新增 false
            bookingId:'',
            userId:'',
            patientPhone:'',
            bookingTime:'',
            userName:'',
            doctorId:"",
            subclinicId:'',
            bookingDesc:'',
            bookingType:0,
            isAdd:1,
            patientName:'',
            patientBirthday:'',
            patientHeight:'',
            patientBodyWeight:'',
            patientGender:0   
        },data || {})
        if(baseFn.notNull(_opts.patientId)){
            _opts.edit = true;
        }
        $('.js_bookingPatient').find('input').prop('disabled',_opts.edit)
        $('.js_bookingPatient').find('select').prop('disabled',_opts.edit)
        $('select.js_bookingType').val(_opts.bookingType)
        if(_opts.bookingType == 0){
            var _html2='<option value="0">继续调理</option>\
                        <option value="1">新病程</option>'
            $('select.js_isAdd').html(_html2)
            $('select.js_isAdd').val(0)
            //显示预约状态
            $('.js_isAdd_wrap').find('label').text('预约状态：')
            $('.js_isAdd_wrap').find('select').removeClass('hidden')
        }else{
            var _html2='<option value="1">新病程</option>'
            $('select.js_isAdd').html(_html2)
            $('select.js_isAdd').val(1)
            //隐藏预约状态
            $('.js_isAdd_wrap').find('label').text(' ')
            $('.js_isAdd_wrap').find('select').addClass('hidden')
            
        }

        //提示窗
        
        if(_opts.lastIsAdd == 1){
            $('.js_bookingInfo_txt_isadd').text('新病程')
        }else{
            $('.js_bookingInfo_txt_isadd').text('继续调理')
        }
        if(_opts.lastBookingType == 1){
            $('.js_bookingInfo_txt_bookingtype').text('预防保健')
            $('.js_bookingInfo_txt_isadd').text('')
        }else{
            $('.js_bookingInfo_txt_bookingtype').text('调理身体')
        }
        if(baseFn.notNull(_opts.lastTime)){
            $('.js_bookingInfo_txt_time').text(baseFn.timestampToTime(_opts.lastTime))
            
        }else{
            $('.js_bookingInfo_txt_time').text('最近无就诊')
            $('.js_bookingInfo_txt_bookingtype').text('无')
            $('.js_bookingInfo_txt_isadd').text('')
        }

        $('.js_patientName').val(_opts.patientName)
        $('.js_patientBirthday').val(_opts.patientBirthday)
        $('.js_patientHeight').val(_opts.patientHeight)
        $('.js_patientWeight').val(_opts.patientBodyWeight)
        $('.js_patientGender').val(_opts.patientGender)
        if(baseFn.notNull(_opts.patientPhones) || baseFn.notNull(_opts.patientPhoness)){
            var _phones = []
            if(baseFn.notNull(_opts.patientPhone)){
                _phones.push(_opts.patientPhone)
            }
            if(baseFn.notNull(_opts.patientPhones)){
                _phones.push(_opts.patientPhones)
            }
            if(baseFn.notNull(_opts.patientPhoness)){
                _phones.push(_opts.patientPhoness)
            }
            $('select.js_patientPhone').removeClass('hidden').prop('disabled',false)
            $('input.js_patientPhone').addClass('hidden').val(_opts.patientPhone)
            var _html=''
            for(var x =0;x<_phones.length;x++){
                _html += '<option id="'+_phones[x]+'">'+_phones[x]+'</option>'
            }
            $('select.js_patientPhone').html(_html).val(_phones[0])
        }else if(!baseFn.notNull(_opts.patientPhones) && !baseFn.notNull(_opts.patientPhoness)){
            $('select.js_patientPhone').addClass('hidden')
            $('input.js_patientPhone').removeClass('hidden').val(_opts.patientPhone)
        }
        
        $('.js_patientDesc').val(_opts.patientDesc)
    },
    bookingTime:{
        timepicker: true,    //开启时间选项
        yearStart: 2000,//设置最小年份
        minDate: 0,
        yearEnd: 2050,        //设置最大年份
        maxDate:false,
        allowTimes: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00','21:00','22:00','23:00'],
        onSelectDate:function(){},
        onSelectTime:function(){
            var _val = $('.js_bookingTime').val()
            if(baseFn.notNull(_val)){
                var selDate = new Date(_val);
                var cutDate = new Date();
                if (selDate < cutDate) {
                    $('.js_bookingTime').val("");
                    alert("请选择当前时间之后的时间段");
                    return;
                }
                var _datas={
                    subclinicId:$('.js_subclinicId').val(),
                    bookingTime:_val+':00'
                }
                selectDoctor(_datas)
            }
        }
    }
}
$('.bespeak_change_look tbody').css('max-height',windowOffsetData.mainWraperHeight-110)
if(baseFn.notNull(DocData.bookingInfo.bookingTime)){
    $('input.js_bookingTime').val(DocData.bookingInfo.bookingTime)

}
/*新增预约*/
// 搜索用户
$('#searchbox').select2({
    placeholder: '请输入宝宝姓名',
    language:{
        noResults:function(){return '<span class="font_blue">没有查询到宝宝！</span>'},
        searching:function(){return '查询中。。。'}
    },
    allowClear: true,
    ajax: {
        url: baseUrl.base+"patient/selectPatient",
        type: "get",
        dataType: 'json',
        data: function (params) {
            return {
                patientName: params.term
            }
        },
        processResults: function (data) {
            var dataResult =[];
            var dataItem = data.results;
            DocData.patientList = dataItem
            for(var i=0;i<dataItem.length;i++){
                var resultObj = {id:'',text:''};
                resultObj['text'] = dataItem[i].patientName + '-' +baseFn.getHidePhoneStr(dataItem[i].patientPhone);
                // resultObj['id'] = dataItem[i].userName + '-' +dataItem[i].userPhone + '-' + dataItem[i].userId;
                resultObj['id'] = dataItem[i].patientId;
                // dataResult.push(resultObj);
                dataItem[i].id=resultObj['id']
                dataItem[i].text=resultObj['text']
                dataResult.push(dataItem[i]);
            }
            return {
                results:dataResult,
            }
        },
        formatResult: function formatRepo(repo){return repo.text;}, // 函数用来渲染结果
        formatSelection: function formatRepoSelection(repo){return repo.text;} // 函数用于呈现当前的选择
    },
    templateResult:function(state){
        // console.log(state)
        if(!state.loading && baseFn.notNull(state.patientPhone)){
            var _html = '<div class="zc_search_select2">'
            _html += '<div class="row">'+
                '<div class="col-sm-4">' +
                    '<div>'+state.patientName + (state.patientGender==0?' 男 ':' 女 ') + (baseFn.notNull(state.patientAge)?state.patientAge:0)+'岁'+'</div>'+
                    '<div>'+baseFn.getHidePhoneStr(state.patientPhone)+'</div>'+
                '</div>'
            _html += '<div class="col-sm-4">' +
                '<div style="text-align:center">第二联系人电话</div>' +
                '<div style="text-align:center">'+((baseFn.notNull(state.patientPhones) && state.patientPhones != '空')?baseFn.getHidePhoneStr(state.patientPhones):'未绑定')+'</div>' +
            '</div>'
            _html += '<div class="col-sm-4">' +
                '<div style="text-align:center">第三联系人电话</div>' +
                '<div style="text-align:center">'+((baseFn.notNull(state.patientPhoness) && state.patientPhones != '空')?baseFn.getHidePhoneStr(state.patientPhoness):'未绑定')+'</div>' +
            '</div>'
            _html += '</div></div>'   
            return _html
        }
    },
    escapeMarkup: function (markup) {return markup; }, // 自定义格式化防止xss注入
    minimumInputLength: function(e){
        var _val = e.term;
        if(/^[\u4e00-\u9fa5]{1,5}$/.test(_val)){
            return 1
        }else{
            return 3
        }
    }//最少输入多少个字符后开始查询
});

$("#searchbox").on("select2:select",function(e){
    $('.js_bookingInfo_txt').removeClass('hidden')
    $('.js_searchbox_wrap').addClass('hidden')
    $('.js_searchtxt_wrap').removeClass('hidden')
    var _val=$(this).val()
    DocData.patientInfo = ''
    if(!baseFn.notNull(DocData.patientList) || DocData.patientList.length == 0){
        DocData.patientInfo = {}
        $('.js_searchtxt_wrap').find('span').text('没有搜索到宝宝，您可以重新搜索，或者直接输入宝宝信息进行预约')
        $('.js_searchtxt_wrap').find('a').text('重新搜索')
    }else{
        DocData.patientInfo = e.params.data;
        if(!baseFn.notNull(DocData.patientInfo)){
            DocData.patientInfo = DocData.patientList[0]
            $('.js_searchtxt_wrap').find('span').text('您选择的宝宝是'+DocData.patientInfo.patientName)
        }else{
            $('.js_searchtxt_wrap').find('span').text('您选择的宝宝是'+DocData.patientInfo.patientName)
        }
        $('.js_searchtxt_wrap').find('a').text('重新选择')
    }
    DocData.newRenderBooking(DocData.patientInfo)
})
$('.js_searchtxt_wrap a.research').on('click',function(){
    $('.js_bookingInfo_txt').addClass('hidden')
    $('.js_searchtxt_wrap').addClass('hidden')
    $('.js_searchbox_wrap').removeClass('hidden')
    $('#searchbox').val(null).trigger('change')
    DocData.newRenderBooking({})
    baseFn.dateTimePick('.js_bookingTime',{
        timepicker: true,    //开启时间选项
        yearStart: 2000,//设置最小年份
        minDate: 0,
        yearEnd: 2050,        //设置最大年份
        allowTimes: [ '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00','21:00','22:00','23:00']
    })
})
//添加预约-保存
$('.edit_ok').click(function () {
    var userId = 1;
    var userPhone = $('#userPhone').val();
    var userName = $('#userName').val();
    //var userGender = $('input:radio:checked').val();
    var bookingTime = $('#bookingTime').val();
    var subclinicId = $('.js_subclinicId').val();
    var doctorId = $('.js_doctorId').val();
    var bookingDesc = $('#bookingDesc').val();
    var _upDatas = {
        "userPhone": $('.js_patientPhone').val(),
        "bookingTime": $('.js_bookingTime').val(),
        "subclinicId": $('.js_subclinicId').val(),
        "doctorId": $('.js_doctorId').val(),
        bookingType:$('.js_bookingType').val(),
        isAdd:$('.js_isAdd').val(),
        "bookingDesc": $('.js_patientDesc').val()
    }
    var _txt=''
    //验证
    if (_upDatas.userPhone == '') {
        _txt = '手机号不能不填哦'
    }
    if(!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_upDatas.userPhone)){
        _txt = '手机号格式不正确'
    }
    if (_upDatas.bookingTime == '') {
        _txt = '需要填写预约时间哦'
    }else{
        _upDatas.bookingTime = _upDatas.bookingTime+':00'
    }
    if (_upDatas.subclinicId == '') {
        // $('#flag4').addClass('hidden');
        // $('#flag5').html("<span class='zcerror' style='color: red;font-size: 8px;'>推拿师非空</span>");
        // return;
        _txt = '需要选择门店'
    }
    if (_upDatas.doctorId == '') {
        // $('#flag4').addClass('hidden');
        // $('#flag5').html("<span class='zcerror' style='color: red;font-size: 8px;'>请选择推拿师</span>");
        _txt = '请选择推拿师'
    }
    
    if(baseFn.notNull(DocData.patientInfo.userId)){
        _upDatas.userId = DocData.patientInfo.userId
    }
    if(baseFn.notNull(DocData.patientInfo.patientId)){
        _upDatas.patientId = DocData.patientInfo.patientId
    }
    
    _upDatas.patientName = $('input.js_patientName').val()
    _upDatas.patientGender = $('select.js_patientGender').val()
    _upDatas.patientBirthday = $('input.js_patientBirthday').val()
    _upDatas.patientHeight = $('input.js_patientHeight').val()
    _upDatas.patientBodyWeight = $('input.js_patientWeight').val()
    if(!baseFn.notNull(_upDatas.patientId) && !baseFn.notNull(_upDatas.userId)){
        if(!baseFn.notNull(_upDatas.patientName)){
            _txt = '请输入宝宝姓名'
        }else if(!baseFn.notNull(_upDatas.patientGender)){
            _txt = '请选择宝宝性别'
        }else if(!baseFn.notNull(_upDatas.patientBirthday)){
            _txt = '请选择宝宝生日'
        }
    }
    if(_txt != ''){
        baseFn.infoDialog(_txt)
        return false
    }
    // console.log(_upDatas)
    // return false
    if(DocData.sendBooking){
        baseFn.infoDialog('预约正在提交中，不要重复操作');
        return false
    }
    DocData.sendBooking=true
    $.ajax({
        type: "POST",
        url: baseUrl.base + "booking/saveBooking",
        data:_upDatas,
        success: function (res) {
            if (res.code == 0) {
                var _results = res.results
                baseFn.dialog({
                    content: '提交成功，是否前往预约列表查看？',
                    okValue: '前往',
                    ok: function () {
                        DocData.bookingInfo.bookingId = _results.bookingId
                        // baseFn.goPath('gotoFastOrder',{
                        //     bookingId:_results.bookingId
                        // })
                        baseFn.goPath('gotoBespeak',{})
                    },
                    cancelValue:'继续添加',
                    cancel: function () {
                        window.location.reload()
                    }
                })
            }else{
                baseFn.infoDialog(res.msg)
            }
        },
        complete:function(){
            DocData.sendBooking=false
        }
    });
});
$('input.js_patientName').on('change',function(){
    var _data = $.trim($(this).val())
    if(baseFn.notNull(DocData.bookingInfo.userId) || baseFn.notNull(DocData.bookingInfo.patientId)){
        return false
    }
    var _data2 = $.trim($('input.js_patientPhone').val())
    if(baseFn.notNull(_data2)){
        baseFn.$get({
            url: "patient/selectPatient",
            data:{patientName:_data},
            calFn:function(res){
                for(var i =0;i<res.length;i++){
                    if(res[i].patientPhone == _data2){
                        DocData.patientInfo = res[i];
                        DocData.newRenderBooking(DocData.patientInfo);
                        break;
                    }else if(res[i].patientPhones == _data2){
                        DocData.patientInfo = res[i];
                        DocData.newRenderBooking(DocData.patientInfo);
                        break;
                    }else if(res[i].patientPhoness == _data2){
                        DocData.patientInfo = res[i];
                        DocData.newRenderBooking(DocData.patientInfo);
                        break;
                    }
                }
            }
        })
    }
})
$('input.js_patientPhone').on('change',function(){
    var _data = $.trim($(this).val())
    if(baseFn.notNull(DocData.bookingInfo.userId) || baseFn.notNull(DocData.bookingInfo.patientId)){
        return false
    }
    var _data2 = $.trim($('input.js_patientName').val())
    if(baseFn.notNull(_data2)){
        baseFn.$get({
            url: "patient/selectPatient",
            data:{patientName:_data},
            calFn:function(res){
                for(var i =0;i<res.length;i++){
                    if(res[i].patientName == _data2){
                        DocData.patientInfo = res[i];
                        DocData.newRenderBooking(DocData.patientInfo);
                        break;
                    }
                }
            }
        })
    }
})
/*新增预约*/
/*基础设置*/
//时间初始化
baseFn.dateTimePick('.js_bookingTime',DocData.bookingTime)
//宝宝生日初始化
baseFn.dateTimePick('.js_patientBirthday',{})
//选择推拿师
function selectDoctor(data){
    baseFn.$get({
        url:baseUrl.booking +"selectFreeDoctor",
        data:data,
        canNull:true,
        calFn:function(res){
            if(baseFn.notNull(res) && res.length != 0){
                $('.js_doctorId').html('')
                for(var x=0;x<res.length;x++){
                    $('.js_doctorId').append("<option value='" + res[x].userId + "'>" + res[x].userName + "</option>");
                }
                if(baseFn.notNull(DocData.bookingInfo.doctorId)){
                    $('.js_doctorId').val(DocData.bookingInfo.doctorId)
                }else{
                    $('.js_doctorId').val(res[0].userId)
                }
            }else{
                $('.js_doctorId').html('')
                baseFn.infoDialog('该门店当前时间段暂无推拿师可以预约',function(){},1000)
            }
        }
    })
}
//选择门店
$.ajax({
    type: "GET",
    url: baseUrl.base + baseUrl.subclinic+"selectSubclinicList",
    data: '',
    success: function (result) {
        if (result.code == 0) {
            DocData.subclinicList=result.results
            var _subData=[]
            for (var i = 0; i < result.results.length; i++) {
                _subData.push({id:result.results[i].subclinicId,text:result.results[i].subclinicName})
            }
            //新增预约弹框
            baseFn.rpSelect('select.js_subclinicId',{
                datas:_subData,
                selFn:function(e){
                    var _upData_ = {
                        subclinicId:e.params.data.id
                    }
                    DocData.bookingInfo.subclinicId = e.params.data.id
                    DocData.bookingInfo.doctorId = ''
                    if(baseFn.notNull($('.js_bookingTime').val())){
                        _upData_.bookingTime = $('.js_bookingTime').val()+':00'
                    }
                    selectDoctor(_upData_)
                    if(baseFn.notNull(DocData.subclinicList) && DocData.subclinicList.length != 0){
                        var _val = e.params.data.id,_acSub=DocData.subclinicList.filter(function(val){
                            return _val == val.subclinicId
                        })[0],_startTime=Number(_acSub.subclinicStartTime),_endTime=Number(_acSub.subclinicEndTime)
                        if(baseFn.notNull($('.js_bookingTime').val())){
                            var _time = Number($('.js_bookingTime').val().substring(11,13))
                            if(_time <_startTime || _time > _endTime){
                                $('.js_bookingTime').val('')
                            }
                        }
                        DocData.bookingTime.allowTimes=[]
                        for(var i=_startTime;i<=_endTime;i++){
                            DocData.bookingTime.allowTimes.push(i+':00')
                        }
                        baseFn.dateTimePick('.js_bookingTime',DocData.bookingTime)
                    }
                },
                calFn:function(){
                    if(SessionData.powerSub){
                        //权限管理 45 门店是否是全部
                        $('select.js_subclinicId').val(SessionData.powerSub).trigger('change');
                        selectDoctor({subclinicId:SessionData.powerSub})
                    }else if(baseFn.notNull(DocData.bookingInfo.subclinicId)){
                        $('select.js_subclinicId').val(DocData.bookingInfo.subclinicId).trigger('change');
                        selectDoctor({subclinicId:DocData.bookingInfo.subclinicId})
                    }
                    console.log(DocData.bookingInfo.subclinicId)
                }
            })
            // $('select.js_subclinicId').on('select2:selecting',function(){
            //     bookingTime = $('.js_bookingTime').val();
            //     if(bookingTime == ''){
            //         baseFn.infoDialog('请先选择预约时间')
            //         return false
            //     }
            // })
            // $('select.js_subclinicId').on('change',function(){
            //     alert(3)
            //     $.get(baseUrl.base + baseUrl.booking +"selectFreeDoctor",{bookingTime:$('.js_bookingTime').val()+':00',subclinicId:$(this).val()},function(res){
            //         if(res.code == '0'){
            //             $('.js_doctorId').find('option').remove()
            //             if (res.results == null) {
            //                 baseFn.infoDialog('该门店当前时间段暂无推拿师可以预约',function(){},1000)
            //                 $('.js_doctorId').append("<option value=''>请选择推拿师</option>");
            //             } else {
            //                 for(var x=0;x<res.results.length;x++){
            //                     $('.js_doctorId').append("<option value='" + res.results[x].userId + "'>" + res.results[x].userName + "</option>");
            //                 }
            //                 if(DocData.bookingInfo.doctorId == ''){
            //                     $('.js_doctorId').val(res.results[0].userId)
            //                 }else{
            //                     $('.js_doctorId').val(DocData.bookingInfo.doctorId)
            //                 }
                            
            //             }
            //         }else{
            //             baseFn.infoDialog(res.msg)
            //         }
            //     },'json')
            // })        
        }
    }
});
$('.js_bookingType').on('change',function(){
    if($(this).val() == 1){
        // $('.js_bookingInfo_txt_bookingtype').text('预防保健')
        // $('.js_isAdd').html('<option value="1">新病程</option>')
        // $('.js_bookingInfo_txt_isadd').text('新病程')
        $('.js_isAdd').val(1)
        //隐藏预约状态
        $('.js_isAdd_wrap').find('label').text(' ')
        $('.js_isAdd_wrap').find('select').addClass('hidden')
    }else{
        // $('.js_bookingInfo_txt_bookingtype').text('调理身体')
        // $('.js_isAdd').html('<option value="0">继续调理</option>\
        // <option value="1">新病程</option>')
        // $('.js_isAdd').val(0)
        // $('.js_bookingInfo_txt_isadd').text('继续调理')
        //显示预约状态
        $('.js_isAdd_wrap').find('label').text('预约状态：')
        $('.js_isAdd_wrap').find('select').removeClass('hidden')
    }

    
})
// $('.js_isAdd').on('change',function(){
//     if($(this).val() == 1){
//         $('.js_bookingInfo_txt_isadd').text('新病程')
//     }else{
//         $('.js_bookingInfo_txt_isadd').text('继续调理')
//     }
// })
// 页面切换逻辑
$('.Baby_Healthy_home_right_top_list>li').on('click', function () {
    // $(this).addClass('bespeak_active').siblings().removeClass('bespeak_active');
});

//顶部tab页面的缓存
if (baseFn.notNull($.session.get('bespeak_tab'))){
    $($.session.get('bespeak_tab')).addClass('bespeak_active').siblings().removeClass('bespeak_active');
}else {
    $('.num1').addClass('bespeak_active').siblings().removeClass('bespeak_active');
}

$('.num1').on('click', function () {
    $.session.set('bespeak_tab','.num1');
    baseFn.goPath('gotoBespeak')
});
$('.num2').on('click', function () {
    $.session.set('bespeak_tab','.num2');
    baseFn.goPath('gotoBespeak',{num:2})
});
$('.num3').on('click', function () {
    $.session.set('bespeak_tab','.num3');
    baseFn.goPath('gotoBespeak',{num:3})
})

//权限管理
// $($('.Baby_Healthy_home_right_top_list>li:not(".hidden")')[0]).trigger('click')

// if(baseFn.notNull(baseFn.getQueryString('num'))){
//     $('.num'+baseFn.getQueryString('num')).trigger('click')
// }
if(baseFn.notNull(baseFn.getQueryString('home'))){
    $('.Baby_Healthy_home_right_bespeak_search .js_addbespeak').trigger('click')
}
